import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useUserStore = defineStore(
  'user', // store id
  () => {
    // 用户信息
    const userId = ref('') // 用户ID
    const username = ref('') // 用户名
    const password = ref('') // 密码（实际项目建议加密存储）
    const account = ref('')  // 账号（如邮箱/手机号）
    const avatar = ref('')   // 头像URL
    const token = ref('')    // 认证Token
    const sessionId = ref('')
    const chatHistory = ref([]) // 对话记录（数组，元素为对象）

     //更新sessionId
     const updatesessionId = (newsessionId) => {
      sessionId.value = newsessionId
     }
  const setUserId = (newId) => {
      userId.value = newId
  }
    // 修改用户名
    const setUsername = (newName) => {
      username.value = newName
    }

    // 修改密码
    const setPassword = (newPassword) => {
      password.value = newPassword
    }

    // 修改账号
    const setAccount = (newAccount) => {
      account.value = newAccount
    }

    // 更新头像
    const updateAvatar = (newAvatarUrl) => {
      avatar.value = newAvatarUrl
    }

    // 设置Token（登录时调用）
    const setToken = (newToken) => {
      token.value = newToken
    }

    // 添加对话记录
   const addChatMessage = (newChat) => {
    if (Array.isArray(newChat)) {
      chatHistory.value = []
      newChat.forEach(chat => {
        chatHistory.value.push({
          sessionId: chat.sessionId,
          title: chat.title,
          createdAt: chat.createdAt || new Date().toISOString(),
          updatedAt: chat.updatedAt || new Date().toISOString()
        });
      })
    }
  } 


    // 清空对话记录
    const clearChatHistory = () => {
      chatHistory.value = []
    }

    // 注销登录（清空所有信息）
    const logout = () => {
      username.value = ''
      password.value = ''
      account.value = ''
      avatar.value = ''
      token.value = ''
      sessionId.value = ''
      chatHistory.value = []
      userId.value = ''
    }

    return {
      username,
      password,
      account,
      avatar,
      token,
      chatHistory,
      userId,
      sessionId,
      setUserId,
      setUsername,
      setPassword,
      setAccount,
      updateAvatar,
      setToken,
      addChatMessage,
      clearChatHistory,
      logout,
      updatesessionId
    }
  },
  {
    persist: true // 开启持久化存储
  }
)